package shedule;

import entities.Channel;
import entities.News;
import parser.news.ChannelParseAdapter;
import parser.news.NewsParser;
import services.ChannelService;
import services.NewsService;
import services.ServiceException;

import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import java.util.List;
import java.util.logging.Level;

/**
 * Class for periodical channels news update
 * <p/>
 * User: kaiser
 * Date: 7/31/13
 * Time: 9:15 PM
 */
@Singleton
@Startup
public class NewsUpdater {

    private final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(NewsUpdater.class.getName());

    @EJB
    NewsService newsService;

    @EJB
    ChannelService channelService;

    /**
     * run news update each 15 min<br/>
     * on every update we get news list,<br/>
     * save it to db, if some of news not exist un DB,<br/>
     * And for each channel remove old not popular<br/>
     * leaving only 100 items for each channel<br/>
     */
    @Schedule(minute = "*/15", hour = "*")
    public void update() {
        logger.info("[NEWS UPDATE START]");
        ChannelParseAdapter adapter = new ChannelParseAdapter();

        logger.log(Level.INFO, "[BEFORE PARSE]");
        List<News> newsList = adapter.getNews(NewsParser.DEFAULT_NEWS_COUNT);
        logger.log(Level.INFO, "[PARSE RESULT: " + newsList.size() + " news]");
        try {
            newsService.addNewNews(newsList);

            List<Channel> channels = channelService.getAllChannels();
            if (channels != null) {
                for (Channel chanel : channels) {

                    newsService.removeOldNotPopularNews(chanel.getId(), NewsParser.DEFAULT_NEWS_COUNT);
                }
            }
        } catch (ServiceException e) {
            logger.log(Level.INFO, e.getMessage());
        }
        logger.info("[NEWS UPDATE END]");
    }
}
